<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="80px" class="search-form">
      <el-form-item label="商品名称" prop="goodsName">
        <el-input
          v-model="queryParams.goodsName"
          placeholder="请输入商品名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="商品分类" prop="classId">
        <el-tree-select
          v-model="selectedClassId"
          :data="classTreeData"
          :props="treeProps"
          placeholder="请选择商品分类"
          clearable
          check-strictly
          :render-after-expand="false"
          @change="handleClassChange"
        />
      </el-form-item>
      <el-form-item label="商品状态" prop="goodsStatus">
        <el-select v-model="queryParams.goodsStatus" placeholder="请选择商品状态" clearable>
          <el-option label="上架" :value="1" />
          <el-option label="下架" :value="0" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['goods:add']"
        >新增商品</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['goods:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['goods:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['goods:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="goodsList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="商品ID" align="center" prop="goodsId" />
      <el-table-column label="商品名称" align="center" prop="goodsName" :show-overflow-tooltip="true" />
      <el-table-column label="商品分类" align="center" prop="className" />
      <el-table-column label="商品价格" align="center" prop="goodsPrice">
        <template #default="scope">
          <span>¥{{ scope.row.goodsPrice }}</span>
        </template>
      </el-table-column>
      <el-table-column label="商品数量" align="center" prop="goodsNumber" />
      <el-table-column label="商品状态" align="center" prop="goodsStatus">
        <template #default="scope">
          <el-switch
            v-model="scope.row.goodsStatus"
            :active-value="1"
            :inactive-value="0"
            @change="handleStatusChange(scope.row)"
          />
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button
            type="text"
            icon="Edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['goods:edit']"
          >修改</el-button>
          <el-button
            type="text"
            icon="Delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['goods:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改商品对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="goodsRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="商品名称" prop="goodsName">
          <el-input v-model="form.goodsName" placeholder="请输入商品名称" />
        </el-form-item>
        <el-form-item label="商品分类" prop="classId">
          <el-tree-select
            v-model="form.classId"
            :data="classTreeData"
            :props="treeProps"
            placeholder="请选择商品分类"
            clearable
            check-strictly
          />
        </el-form-item>
        <el-form-item label="商品价格" prop="goodsPrice">
          <el-input v-model="form.goodsPrice" placeholder="请输入商品价格" type="number" />
        </el-form-item>
        <el-form-item label="商品数量" prop="goodsNumber">
          <el-input v-model="form.goodsNumber" placeholder="请输入商品数量" type="number" />
        </el-form-item>
        <el-form-item label="商品状态" prop="goodsStatus">
          <el-radio-group v-model="form.goodsStatus">
            <el-radio :label="1">上架</el-radio>
            <el-radio :label="0">下架</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Goods">
import { listGoods, getGoods, delGoods, addGoods, updateGoods, changeGoodsStatus } from "@/api/goods";
import { getGoodsCategoryTree } from "@/api/goods";

const { proxy } = getCurrentInstance();
const router = useRouter();

const goodsList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const classTreeData = ref([]);
const selectedClassId = ref(null);

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    goodsName: null,
    classId: null,
    goodsStatus: null
  },
  rules: {
    goodsName: [
      { required: true, message: "商品名称不能为空", trigger: "blur" }
    ],
    classId: [
      { required: true, message: "请选择商品分类", trigger: "change" }
    ],
    goodsPrice: [
      { required: true, message: "商品价格不能为空", trigger: "blur" }
    ],
    goodsNumber: [
      { required: true, message: "商品数量不能为空", trigger: "blur" }
    ]
  }
});

const { queryParams, form, rules } = toRefs(data);

const treeProps = {
  value: 'id',
  label: 'name',
  children: 'children'
};

/** 查询商品列表 */
function getList() {
  loading.value = true;
  listGoods(queryParams.value).then(response => {
    goodsList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

/** 获取商品分类树 */
function getClassTree() {
  getGoodsCategoryTree().then(response => {
    classTreeData.value = response.data;
  });
}

/** 取消按钮 */
function cancel() {
  open.value = false;
  reset();
}

/** 表单重置 */
function reset() {
  form.value = {
    goodsId: null,
    goodsName: null,
    classId: null,
    goodsPrice: null,
    goodsNumber: null,
    goodsStatus: 1
  };
  proxy.resetForm("goodsRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  selectedClassId.value = null;
  handleQuery();
}

/** 分类选择变化 */
function handleClassChange(value) {
  queryParams.value.classId = value;
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.goodsId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  router.push('/lkshop/goods/add');
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const goodsId = row.goodsId || ids.value[0];
  getGoods(goodsId).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改商品";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["goodsRef"].validate(valid => {
    if (valid) {
      if (form.value.goodsId != null) {
        updateGoods(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addGoods(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const goodsIds = row.goodsId || ids.value;
  proxy.$modal.confirm('是否确认删除商品编号为"' + goodsIds + '"的数据项？').then(function() {
    return delGoods(goodsIds);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 状态修改 */
function handleStatusChange(row) {
  let text = row.goodsStatus === "1" ? "启用" : "停用";
  proxy.$modal.confirm('确认要"' + text + '""' + row.goodsName + '"商品吗？').then(function() {
    return changeGoodsStatus(row.goodsId, row.goodsStatus);
  }).then(() => {
    proxy.$modal.msgSuccess(text + "成功");
  }).catch(function() {
    row.goodsStatus = row.goodsStatus === "1" ? "0" : "1";
  });
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('goods/export', {
    ...queryParams.value
  }, `goods_${new Date().getTime()}.xlsx`);
}

getList();
getClassTree();
</script> 